﻿using Ljy_VoteSys.Models.Database;
using Ljy_VoteSys.Service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace Ljy_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AddUSERController : Controller //注册
    {
        //注入jwt服务
        private readonly IJWTService _jwtService;
        //定义数据库上下文
        private readonly Ljy_VoteSysContext _db;

        public AddUSERController(IJWTService jwtService, Ljy_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }
        //注册用户
        /// <summary>
        /// 普通用户....
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string AddUser(User request)
        {
            //唯一的用户名
            //当数据库存在这个用户名时 做出响应
            //存在
            // 电子邮箱的正则表达式
            var emailRegex = new Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");

            if (!emailRegex.IsMatch(request.Username))
            {
                return "用户名不是有效的电子邮箱地址";
            }
            if (_db.UserTables.Any(x => x.Username == request.Username))
            {
                return "用户名已存在";
            }
            var salt = new Random().Next(100000, 999999).ToString();
            var md5 = Md5.MD5Encrypt32(request.Pwd + salt);
            var user = new UserTable
            {
                Username = request.Username,
                Pwd = md5,
                Solt=salt

            };
            _db.UserTables.Add(user);
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        //注册企业用户
        //注册用户
        /// <summary>
        /// 企业用户...
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string AddCompanyuser(CompanyUser request)
        {
            //唯一的用户名
            //当数据库存在这个用户名时 做出响应
            //存在
            // 电子邮箱的正则表达式
            var emailRegex = new Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");

            if (!emailRegex.IsMatch(request.CompanyUser1))
            {
                return "用户名不是有效的电子邮箱地址";
            }
            if (_db.CompanyUsers.Any(x => x.CompanyUser1 == request.CompanyUser1))
            {
                return "用户名已存在";
            }
            var salt = new Random().Next(100000, 999999).ToString();
            var md5 = Md5.MD5Encrypt32(request.Pwd + salt);
            var User = new CompanyUser
            {
                CompanyUser1 = request.CompanyUser1,
                Pwd = md5,
                Solt = salt
            };
            _db.CompanyUsers.Add(User);
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

    }


}
